package com.heima.article.service.impl;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 生成静态文件上传到minIO中
     *
     * @param apArticle
     * @param content
     */
    @Override
    @Async
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        if (StringUtils.isNotEmpty(content)) {
            try {
                // 1.获取模板
                Template template = configuration.getTemplate("article.ftl");
                // 2.封装数据
                Map<String, Object> map = new HashMap<>();
                map.put("content", JSONArray.parseArray(content));
                // 3.生成html文件
                StringWriter out = new StringWriter();
                template.process(map, out);
                // 4.上传到minio
                InputStream is = new ByteArrayInputStream(out.toString().getBytes());
                String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", is);
                // 5.更新article表static_url字段
                apArticle.setStaticUrl(path);
                apArticleMapper.updateById(apArticle);
                // 6.同步数据到es
                SearchArticleVo vo = new SearchArticleVo();
                BeanUtils.copyProperties(apArticle, vo);
                vo.setContent(content);
                vo.setStaticUrl(path);
                kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
